import { Request, Response, NextFunction } from 'express'
import { verifyToken } from '../utils/jwt'
import { User } from '../models/User'
import { AuthRequest } from '../types'

export const authMiddleware = async (
  req: AuthRequest, 
  res: Response, 
  next: NextFunction
): Promise<void> => {
  try {
    const authHeader = req.headers.authorization
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      res.status(401).json({ 
        success: false, 
        message: '请提供有效的认证token' 
      })
      return
    }

    const token = authHeader.substring(7)
    const decoded = verifyToken(token)
    
    const user = await User.findById(decoded.id)
    if (!user) {
      res.status(401).json({ 
        success: false, 
        message: '用户不存在' 
      })
      return
    }

    req.user = {
      id: user._id.toString(),
      email: user.email,
      username: user.username
    }

    next()
  } catch (error) {
    res.status(401).json({ 
      success: false, 
      message: '认证失败，请重新登录' 
    })
  }
}